from flask import Flask, render_template, request, session, url_for, redirect, flash
from flask_sqlalchemy import SQLAlchemy
# from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'  # 使用 SQLite 数据库
# app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:123456@127.0.0.1:3306/test?charset=utf8"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
# app = Flask(__name__)
# migrate = Migrate(app, db)

app.secret_key = "zjou"



class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), unique=True, nullable=False)
    password = db.Column(db.String(100), nullable=False)
    is_admin = db.Column(db.Boolean, default=False, nullable=False)

class Major(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    students = db.relationship('Student', backref='major', lazy=True)
    teachers = db.relationship('Teacher', backref='major', lazy=True)

class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False)
    age = db.Column(db.Integer, nullable=False)
    gender = db.Column(db.String(10), nullable=False)
    password = db.Column(db.String(100), nullable=False)
    major_id = db.Column(db.Integer, db.ForeignKey('major.id'), nullable=False)
    course_id = db.Column(db.Integer, db.ForeignKey('course.id'), nullable=True)
    # major = db.relationship('Major', backref=db.backref('students', lazy=True))

class Teacher(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False)
    age = db.Column(db.Integer, nullable=False)
    gender = db.Column(db.String(10), nullable=False)
    title = db.Column(db.String(100), nullable=False)
    password = db.Column(db.String(100), nullable=False)
    major_id = db.Column(db.Integer, db.ForeignKey('major.id'), nullable=False)
    # major = db.relationship('Major', backref=db.backref('teachers', lazy=True))

class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    teacher_id = db.Column(db.Integer, db.ForeignKey('teacher.id'), nullable=False)
    teacher = db.relationship('Teacher', backref=db.backref('courses', lazy=True))
    student = db.relationship('Student', backref=db.backref('course', lazy=True))

# class Enrollment(db.Model):
#     id = db.Column(db.Integer, primary_key=True)
#     student_id = db.Column(db.Integer, db.ForeignKey('student.id'), nullable=False)
#     course_id = db.Column(db.Integer, db.ForeignKey('course.id'), nullable=False)
#     student = db.relationship('Student', backref='enrollments')
#     course = db.relationship('Course', backref='enrolled_students')




with app.app_context():
    db.create_all()
    if not User.query.filter_by(username='admin').first():
        admin_user = User(username='admin', password='admin', is_admin=True)    # 初始化管理员
        db.session.add(admin_user)
        db.session.commit()



# --------------------------------  Users  --------------------------------

# 注册
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        confirm_password = request.form['confirm_password']
        if password != confirm_password:
            flash('两次输入的密码不一致！')
            return redirect(url_for('register'))
        user_type = request.form['user_type']  # 'student' 或 'teacher'
        if Student.query.filter_by(username=username).first() or Teacher.query.filter_by(username=username).first():
            flash(f'{user_type}已存在！')
            return redirect(url_for('register'))
        else:
            if user_type == 'student':
                new_user = Student(username=username, password=password, age=0, gender='未指定', major_id=1)  # 默认数据
                db.session.add(new_user)
            else:
                new_user = Teacher(username=username, password=password, age=0, gender='未指定', title='未指定', major_id=1)  # 默认数据
                db.session.add(new_user)

        db.session.commit()
        flash(f'{user_type}注册成功！')
        return redirect(url_for('login'))
    
    return render_template('register.html')


# --------------------------------  Login  --------------------------------

# 登录页面（简化版）
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username', '')
        password = request.form.get('password', '')
        user = User.query.filter_by(username=username, password=password).first() or \
               Student.query.filter_by(username=username, password=password).first() or \
               Teacher.query.filter_by(username=username, password=password).first()
        
        if user:
            session['uid'] = user.id
            if isinstance(user, User):
                session['is_admin'] = True
                session['role'] = 'admin'
                return redirect(url_for('list_majors'))
            elif isinstance(user, Student):
                session['is_admin'] = False
                session['role'] = 'student'
                return redirect(url_for('list_students'))
            elif isinstance(user, Teacher):
                session['is_admin'] = False
                session['role'] = 'teacher'
                return redirect(url_for('list_teachers'))
        else:
            flash('用户名或密码错误！')
        # if user:
        #     session['uid'] = user.id
        #     session['is_admin'] = getattr(user, 'is_admin', False)     # 如果没有 is_admin 属性，则默认为 False
        #     if isinstance(user, User) and user.is_admin:
        #         return redirect(url_for('list_majors'))
        #     else:
        #         return redirect(url_for('list_students'))
        # else:
        #     flash('用户名或密码错误！')
    return render_template('login.html')


# 登出
@app.route('/logout')
def logout():
    session.pop('uid', None)
    session.pop('is_admin', None)
    return redirect(url_for('login'))

@app.route("/")
def home():
    return  redirect(url_for('login'))




# --------------------------------  Majors  --------------------------------

# 查看专业信息
@app.route('/majors')
def list_majors():
    if "uid" not in session:
        return render_template("login.html")
    majors = Major.query.all()
    return render_template('majors.html', majors=majors)

# 添加专业
@app.route('/add_major', methods=['GET', 'POST'])
def add_major():
    if "uid" not in session or not session['is_admin']:
        return redirect(url_for('login'))
    if request.method == 'POST':
        name = request.form['name']
        new_major = Major(name=name)
        db.session.add(new_major)
        db.session.commit()
        flash('专业添加成功！')
        return redirect(url_for('list_majors'))
    return render_template('add_major.html')

# 修改专业
@app.route('/edit_major/<int:id>', methods=['GET', 'POST'])
def edit_major(id):
    if "uid" not in session or not session['is_admin']:
        return redirect(url_for('login'))
    major = Major.query.get_or_404(id)
    if request.method == 'POST':
        major.name = request.form['name']
        db.session.commit()
        flash('专业信息修改成功！')
        return redirect(url_for('list_majors'))
    return render_template('edit_major.html', major=major)

# 删除专业
@app.route('/delete_major/<int:id>')
def delete_major(id):
    if "uid" not in session or not session['is_admin']:
        return redirect(url_for('login'))
    major = Major.query.get_or_404(id)
    db.session.delete(major)
    db.session.commit()
    flash('专业删除成功！')
    return redirect(url_for('list_majors'))




# --------------------------------  Students  --------------------------------


# 查看学生信息
@app.route('/students')
def list_students():
    if "uid" not in session:
        return render_template("login.html")
    students = Student.query.all()
    is_admin = session.get('is_admin', False)
    return render_template('students.html', students=students, is_admin=is_admin)

# 添加学生
@app.route('/add_student', methods=['GET', 'POST'])
def add_student():
    if "uid" not in session or not session['is_admin']:
        return redirect(url_for('login'))
    if request.method == 'POST':
        username = request.form['username']
        age = request.form['age']
        gender = request.form['gender']
        major_id = request.form['major_id']
        defalut_password = '123456'  # 默认密码
        course_id = request.form.get('course', 0)   # 未选课就像专业一样设置未选课
        # if course_id is None:
        #     new_student = Student(username=username, age=age, gender=gender, major_id=major_id, password=defalut_password)
        # else:
        #     new_student = Student(username=username, age=age, gender=gender, major_id=major_id, password=defalut_password, course_id=course_id)
        new_student = Student(username=username, age=age, gender=gender, major_id=major_id, password=defalut_password, course_id=course_id)
        db.session.add(new_student)
        db.session.commit()
        flash('学生添加成功！')
        return redirect(url_for('list_students'))
    majors = Major.query.all()
    courses = Course.query.all()
    return render_template('add_student.html', majors=majors, course=courses)

# 修改学生
@app.route('/edit_student/<int:id>', methods=['GET', 'POST'])
def edit_student(id):
    if "uid" not in session:
        return redirect(url_for('login'))
    student = Student.query.get_or_404(id)
    is_admin = session.get('is_admin', False)
    if request.method == 'POST':
        student.username = request.form['username']
        student.age = request.form['age']
        student.gender = request.form['gender']
        student.major_id = request.form['major_id']
        if is_admin or ( session['role'] == 'student' and student.id == session['uid']):  # 管理员或自己修改自己的信息
            password = request.form.get('password', None)
            if password:
                student.password = password

        db.session.commit()
        flash('学生信息修改成功！')
        return redirect(url_for('list_students'))
    majors = Major.query.all()
    return render_template('edit_student.html', student=student, majors=majors, is_admin=is_admin)

# 删除学生
@app.route('/delete_student/<int:id>')
def delete_student(id):
    if "uid" not in session or not session['is_admin']:
        return redirect(url_for('login'))
    student = Student.query.get_or_404(id)
    db.session.delete(student)
    db.session.commit()
    flash('学生删除成功！')
    return redirect(url_for('list_students'))

# 学生选课
@app.route('/select_course/<int:id>', methods=['GET', 'POST'])
def select_course(id):
    if "uid" not in session:
        return redirect(url_for('login'))
    student = Student.query.get_or_404(id)
    if request.method == 'POST':
        course_id = request.form['course_id']
        student.course_id = course_id
        db.session.commit()
        flash('选课成功！')
        return redirect(url_for('list_students'))
    courses = Course.query.all()
    return render_template('select_course.html', student=student, courses=courses)

# 学生退课
@app.route('/cancel_course/<int:id>')
def cancel_course(id):
    if "uid" not in session:
        return redirect(url_for('login'))
    student = Student.query.get_or_404(id)
    student.course_id = None
    db.session.commit()
    flash('退课成功！')
    return redirect(url_for('list_students'))





# --------------------------------  Teachers  --------------------------------

# 查看教师信息
@app.route('/teachers')
def list_teachers():
    if "uid" not in session:
        return render_template("login.html")
    teachers = Teacher.query.all()
    is_admin = session.get('is_admin', False)
    return render_template('teachers.html', teachers=teachers, is_admin=is_admin)

# 添加教师
@app.route('/add_teacher', methods=['GET', 'POST'])
def add_teacher():
    if "uid" not in session or not session['is_admin']:
        return redirect(url_for('login'))
    if request.method == 'POST':
        username = request.form['username']
        age = request.form['age']
        gender = request.form['gender']
        title = request.form['title']
        major_id = request.form['major_id']
        defalut_password = '123456'  # 默认密码
        new_teacher = Teacher(username=username, age=age, gender=gender, title=title, major_id=major_id, password=defalut_password)
        db.session.add(new_teacher)
        db.session.commit()
        flash('教师添加成功！')
        return redirect(url_for('list_teachers'))
    majors = Major.query.all()
    return render_template('add_teacher.html', majors=majors)

# 修改教师
@app.route('/edit_teacher/<int:id>', methods=['GET', 'POST'])
def edit_teacher(id):
    if "uid" not in session:
        return redirect(url_for('login'))
    teacher = Teacher.query.get_or_404(id)
    is_admin = session.get('is_admin', False)
    if request.method == 'POST':
        teacher.username = request.form['username']
        teacher.age = request.form['age']
        teacher.gender = request.form['gender']
        teacher.title = request.form['title']
        teacher.major_id = request.form['major_id']
        if is_admin or ( session['role'] == 'teacher' and teacher.id == session['uid']):  # 管理员或自己修改自己的信息
            password = request.form.get('password', None)
            if password:
                teacher.password = password
        
        db.session.commit()
        flash('教师信息修改成功！')
        return redirect(url_for('list_teachers'))
    majors = Major.query.all()
    return render_template('edit_teacher.html', teacher=teacher, majors=majors, is_admin=is_admin)

# 删除教师
@app.route('/delete_teacher/<int:id>')
def delete_teacher(id):
    if "uid" not in session or not session['is_admin']:
        return redirect(url_for('login'))
    teacher = Teacher.query.get_or_404(id)
    db.session.delete(teacher)
    db.session.commit()
    flash('教师删除成功！')
    return redirect(url_for('list_teachers'))





# --------------------------------  Courses  --------------------------------

# 查看课程信息
@app.route('/courses', methods=['GET'])
def list_courses():
    if "uid" not in session:
        return redirect(url_for('login'))
    
    courses = Course.query.all()  # 获取所有课程
    return render_template('courses.html', courses=courses)


# 添加课程
@app.route('/add_course', methods=['GET', 'POST'])
def add_course():
    if "uid" not in session or not session['is_admin']:
        return redirect(url_for('login'))
    if request.method == 'POST':
        name = request.form['name']
        teacher_id = request.form['teacher_id']
        new_course = Course(name=name, teacher_id=teacher_id)
        db.session.add(new_course)
        db.session.commit()
        flash('课程添加成功！')
        return redirect(url_for('list_courses'))
    teachers = Teacher.query.all()
    return render_template('add_course.html', teachers=teachers)

# 修改课程
@app.route('/edit_course/<int:id>', methods=['GET', 'POST'])
def edit_course(id):
    if "uid" not in session or not session['is_admin']:
        return redirect(url_for('login'))
    course = Course.query.get_or_404(id)
    if request.method == 'POST':
        course.name = request.form['name']
        course.teacher_id = request.form['teacher_id']
        db.session.commit()
        flash('课程信息修改成功！')
        return redirect(url_for('list_courses'))
    teachers = Teacher.query.all()
    return render_template('edit_course.html', course=course, teachers=teachers)

# 删除课程
@app.route('/delete_course/<int:id>')
def delete_course(id):
    if "uid" not in session or not session['is_admin']:
        return redirect(url_for('login'))
    course = Course.query.get_or_404(id)
    db.session.delete(course)
    db.session.commit()
    flash('课程删除成功！')
    return redirect(url_for('list_courses'))



# --------------------------------  Enrollments  --------------------------------

# # 选课
# @app.route('/enroll/<int:course_id>', methods=['POST'])
# def enroll_course(course_id):
#     if "uid" not in session:
#         return redirect(url_for('login'))
    
#     student_id = session['uid']
#     # 检查是否已经选了该课程
#     if Enrollment.query.filter_by(student_id=student_id, course_id=course_id).first():
#         flash('你已经选过这门课了！')
#     else:
#         enrollment = Enrollment(student_id=student_id, course_id=course_id)
#         db.session.add(enrollment)
#         db.session.commit()
#         flash('选课成功！')

#     return redirect(url_for('list_courses'))  # 选课成功后重定向到课程列表


# # 退课
# @app.route('/drop/<int:course_id>', methods=['POST'])
# def drop_course(course_id):
#     if "uid" not in session:
#         return redirect(url_for('login'))
    
#     student_id = session['uid']
#     enrollment = Enrollment.query.filter_by(student_id=student_id, course_id=course_id).first()
#     if enrollment:
#         db.session.delete(enrollment)
#         db.session.commit()
#         flash('退课成功！')
#     else:
#         flash('未找到该课程的选课记录！')

#     return redirect(url_for('list_courses'))






if __name__ == "__main__":
    app.run(debug=True)
